/* eslint-disable no-useless-escape */

export function getQueryString(name) {
  let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  let r = window.location.search.substr(1).match(reg)
  if (r != null) return decodeURI(r[2])
  return null
}

export function once(dom, event, callback) {
  let handle = e => {
    callback(e)
    dom.removeEventListener(event, handle)
  }
  dom.addEventListener(event, handle)
}

/**
 * 函数执行一次
 */
export class RunOnce {
  constructor(callBack) {
    this.callBack = callBack
    this.done = false
  }
  run() {
    if (this.done) return
    this.callBack && this.callBack()
    this.done = true
  }
  setCallBack(callBack) {
    if (this.done) return
    this.callBack = callBack
  }
}

export function funcUrlDel(name) {
  let loca = window.location
  let baseUrl = loca.origin + loca.pathname + '?'
  let query = loca.search.substr(1)
  if (query.indexOf(name) > -1) {
    let obj = {}
    let arr = query.split('&')
    for (let i = 0; i < arr.length; i++) {
      arr[i] = arr[i].split('=')
      obj[arr[i][0]] = arr[i][1]
    }
    delete obj[name]
    let url =
      baseUrl +
      JSON.stringify(obj)
        .replace(/[\"\{\}]/g, '')
        .replace(/\:/g, '=')
        .replace(/\,/g, '&')
    return url
  }
}
